/*
This file is part of buco.  
Copyright (c) 2012 Christopher Pawelzik <christopher@cpawelzik.com>

Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php 
*/ 
package buco.http;

import java.io.File;

import javax.servlet.ServletException;

import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceEvent;
import org.osgi.framework.ServiceListener;
import org.osgi.framework.ServiceReference;
import org.osgi.service.http.HttpService;
import org.osgi.service.http.NamespaceException;
import javax.servlet.http.HttpSessionListener;

/**
 * @author Christopher
 *
 */
public class Activator implements BundleActivator, ServiceListener {

	private BundleContext m_ctx; 
	
	@Override
	public void start(BundleContext ctx) throws Exception {
		m_ctx = ctx;
		String filter = "(objectclass=" + HttpService.class.getName() + ")";
		ctx.addServiceListener(this, filter); 		
		ctx.registerService(HttpSessionListener.class.getName(), new SessionListener(), null);
	}

	@Override
	public void stop(BundleContext ctx) throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	@SuppressWarnings("rawtypes")
	public void serviceChanged(ServiceEvent ev) {
		if(ev.getType() == ServiceEvent.REGISTERED) { 		    
			ServiceReference sRef = m_ctx.getServiceReference(HttpService.class.getName());	    	    
		    if (sRef != null)
		    {
		    	@SuppressWarnings("unchecked")
				HttpService service = (HttpService) m_ctx.getService(sRef);
		    	
			    try {			    	
			    	// Register JSON-RPC Adapter servlet
					service.registerServlet("/json-rpc", new JsonRpcServlet(), null, null);
					System.out.println("Registered JSON-RPC servlet.");
					
					// Register File servlet
					service.registerServlet("/composition", new FileServlet(), null, null);
					System.out.println("Registered File servlet.");
					
			    	// Register resources for web client 			    	
			    	String path = new File(System.getProperty("user.dir"), "wwwroot").getAbsolutePath(); 
			    	service.registerResources("/", "", new WebClientHttpContext(path));
			    	System.out.println("Registered Web Client in: " + path); 			    
				} catch (ServletException e) {		
					e.printStackTrace();
				} catch (NamespaceException e) { 
					e.printStackTrace();
				}			   			   
		    }
		}
		
	}

}
